from flask import render_template, current_app, session, request, jsonify, g

from info.constants import CLICK_RANK_MAX_NEWS
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from info import redis_store
@index_blu.route('/')
@user_login_data
def index():
    # session['name'] = 'itcast'
    # 向redis保存一个值
    # redis_store.set('name','dreamy')
    """
    如果用户已经登录，将当前用户的数据传到模板中
    :return:
    """
    # user_id = session.get('user_id','')
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user

    # 右侧新闻排行
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 新闻分类信息
    category_list = None
    try:
        category_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_dict_li = []
    for category in category_list:
        category_dict_li.append(category.to_dict())

    data = {
        "user":user.to_dict() if user else None,
        "news_list_li":news_dict_li,
        "category_dict_li":category_dict_li
    }
    print(data['category_dict_li'])
    return render_template('news/index.html',data=data)


# 字啊打开网页的时候，浏览器会默认去请求根路径+favicon.ico做网站标签的小图标
# send_static_file是flask查找静态文件所调用的方法
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')

@index_blu.route('/news_list')
def news_list():
    """
    1、获取参数
    # # params @cid 当前新闻分类id
    # # params @page 第几页
    # # params @per_page 每页显示几条数据
    :return:
    """
    # 1、获取参数
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')

    # 2、校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    # 3、查询数据
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')

    news_list = paginate.items # 模型对象列表
    total_pages = paginate.pages
    current_page= paginate.page

    # news_dict_li = []
    # for news in news_list:
    #     news_dict_li.append(news.to_dict())

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    data = {

        "total_pages":total_pages,
        "current_page":current_page,
        "news_dict_li": news_dict_li
    }
    # print(data)
    return jsonify(errno=RET.OK,errmsg='ok',data=data)